package leetcode.code0564;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

//	System.out.println(tryme);
//	System.out.println(trymin);
//	System.out.println(trymax);
//	System.out.println(min);
//	System.out.println(max);

	public String nearestPalindromic(String n) {
		long len = n.length();
		if (len == 1) {
			return String.valueOf(Integer.valueOf(n) - 1);
		}
		long me = Long.valueOf(n);
		boolean odd = (len & 1) == 1;
		long half = (len + 1) >> 1;
		char[] cs = n.toCharArray();
		long h = 0;
		int p = 0;
		while (p < half) {
			h = h * 10 + cs[p] - '0';
			p++;
		}
		long try1 = this.pal(h, half, odd);
		long try2 = this.pal(h - 1, half, odd);
		long try3 = this.pal(h + 1, half, odd);
		long try4 = (long) Math.pow(10, len - 1) - 1;
		long try5 = (long) Math.pow(10, len) + 1;
//		System.out.println(try1);
//		System.out.println(try2);
//		System.out.println(try3);
//		System.out.println(try4);
//		System.out.println(try5);
		long ans = try2;
		ans = this.findAns(me, ans, try1);
		ans = this.findAns(me, ans, try3);
		ans = this.findAns(me, ans, try4);
		ans = this.findAns(me, ans, try5);
		return String.valueOf(ans);
	}

	private long findAns(long me, long ans, long other) {
		if (me != other) {
			if (Math.abs(me - ans) > Math.abs(me - other)) {
				ans = other;
			} else if (Math.abs(me - ans) == Math.abs(me - other)) {
				ans = Math.min(ans, other);
			}
		}
		return ans;
	}

	private long pal(long try1, long len, boolean odd) {
		len -= odd ? 1 : 0;
		long basic = (long) Math.pow(10, len);
		long ans = try1 * basic;
		long mirror = 0;
		try1 = odd ? try1 / 10 : try1;
		while (try1 > 0) {
			long cur = try1 % 10;
			mirror = mirror * 10 + cur;
			try1 /= 10;
		}
		return ans + mirror;
	}

	@Override
	public void debug1() {
		HelpDebug.compare("88", this.nearestPalindromic("91"));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub
		HelpDebug.compare("1221", this.nearestPalindromic("1213"));

	}

	@Override
	public void debug3() {
		HelpDebug.compare("9", this.nearestPalindromic("11"));
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		HelpDebug.compare("1837667381", this.nearestPalindromic("1837722381"));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug3();
		so.debug4();
		so.debug1();
		so.debug2();
//		so.nearestPalindromic("1234");

	}

}
